<?php

namespace App\Http\Services;

use App\Exceptions\ErrorCodeException;
use App\Exceptions\PublicException;
use App\Http\Model\Ad;
use App\Http\Model\Counter;
use App\Http\Model\CustomGame;
use App\Http\Model\Gift;
use App\Http\Model\GiftBag;
use App\Http\Model\GiftDoubleHitStatistics;
use App\Http\Model\GiftLibrary;
use App\Http\Model\FinanceRechargeOrder;
use App\Http\Model\Hint;
use App\Http\Model\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class CounterServices extends CommonServices
{

    protected $modelCounter;
    protected $modelGift;
    protected $modelGiftBag;
    protected $doubleHitStatistics;
    protected $rechargeModel;
    protected $adModel;
    protected $testuser = 'QX:TESTUSER'; //string QX:TESTUSER =>{json} 七夕测试用户
    protected $roomTestList = 'ROOMTEST:LIST'; //string ROOMTEST:LIST =>{json} 测试房间
    protected $nationalStartTime = '1695744000';//礼品角标开始时间9-27 00:00:00
    protected $nationalEndTime = '1696607999';//国庆角标结束时间10-06 00:00:00
    protected $userModel;
    protected $customModel;

    public function __construct()
    {
        parent::__construct();
        $this->modelCounter = new Counter();
        $this->modelGift = new Gift();
        $this->modelGiftBag = new GiftBag();
        $this->doubleHitStatistics = new GiftDoubleHitStatistics();
        $this->rechargeModel = new FinanceRechargeOrder();
        $this->adModel = new Ad();
        $this->userModel  = new User();
        $this->customModel = new CustomGame();
    }

    public function getCounter($roomId, $id, $cateId = 0, $cur_user_id)
    {
        $now = time();

        $counterArr = $this->modelCounter->getCounter($id, $cateId, 0);
        $giftArr = $this->modelGift->getAllV2();
        $giftArr = array_column($giftArr, null, 'gift_id');

        // 礼物玩法
        $newPlayList = $this->modelCounter->getCounterNewPlay();
        $newPlayMap = array_column($newPlayList, null, 'counter_id');
        foreach ($counterArr as $k => $v) {
            $counterArr[$k]['exp_action'] = '';
            $counterArr[$k]['ext_data'] = '';
            $counterArr[$k]['gift_resource'] = '';
            $counterArr[$k]['classification'] = 0;
            $counterArr[$k]['classification_config'] = new \stdClass();
            if (!empty($counterArr[$k]['exp_url'])) {
                $counterArr[$k]['exp_action'] = sprintf("yyaudio://web?url=%s&type=0", urlencode($counterArr[$k]['exp_url']));
            }

            if (isset($newPlayMap[$v['id']])) $counterArr[$k]['play_info'] = $newPlayMap[$v['id']];

            // goods_type 1=钻石礼物
            unset($counterArr[$k]['exp_url']);
            if ($counterArr[$k]['goods_type'] == 1) {
                $counterArr[$k]['pay_type'] = 1;
                $counterArr[$k]['price'] = $giftArr[$counterArr[$k]['goods_id']]['price'];
                $counterArr[$k]['gift_type'] = $giftArr[$counterArr[$k]['goods_id']]['gift_type'];
                $counterArr[$k]['ext_data'] = $giftArr[$counterArr[$k]['goods_id']]['ext_data'];
                $counterArr[$k]['gift_resource'] = $giftArr[$counterArr[$k]['goods_id']]['animate_resource'];
                if (empty($counterArr[$k]['name'])) {
                    $counterArr[$k]['name'] = $giftArr[$counterArr[$k]['goods_id']]['name'];
                }
                if (empty($counterArr[$k]['image'])) {
                    $counterArr[$k]['image'] = $giftArr[$counterArr[$k]['goods_id']]['image'];
                }
                if ($giftArr[$counterArr[$k]['goods_id']]['gift_label_id']) {
                    $label_image = $this->modelGift->getGiftLabelRes($giftArr[$counterArr[$k]['goods_id']]['gift_label_id'], 'image');
                    if (!empty($label_image)) {
                        $counterArr[$k]['label_image'] = getPicDomain() . $label_image;
                    }
                }

                //礼物icon
                if (in_array($counterArr[$k]['goods_type'],[1])) {
                    //冠名礼物
                    $namingUserId = $this->modelGift->getGiftNaming($counterArr[$k]['goods_id']);
                    if (!empty($namingUserId)) {
                        $namingUserInfo = $this->user->get_user($namingUserId);
                        if (!empty($namingUserInfo)) {
                            $counterArr[$k]['naming_user'] = [
                                "user_id" => $namingUserInfo['user_id'],
                                "user_uid" => $namingUserInfo['user_uid'],
                                "nickname" => $namingUserInfo['nickname'],
                                "gender" => $namingUserInfo['gender'],
                                "image" => empty($namingUserInfo['images'][0]) ? "" : $namingUserInfo['images'][0],
                            ];
                        }
                    }
                    //周星礼物
                    $counterArr[$k]['top_left_corner'] = '';
                    $giftStar = $this->modelGift->getGiftstarConfig($counterArr[$k]['goods_id']);
                    if ($giftStar) {
                        $counterArr[$k]['top_left_corner'] = build_image('/icon/giftStar.png');
                    }
                    
                    //点唱icon
                    if(in_array($counterArr[$k]['goods_id'], [28,247,251,252,253,254,257,258,259,8,471])) {
                        $counterArr[$k]['top_left_corner'] = build_image('/icon/mic.png');
                    }

                    //幸运礼物
                    if(in_array($counterArr[$k]['goods_id'], [132, 133, 153,154,155, 149, 404, 527,443,363,347,660,661,662,663])) {
                        $counterArr[$k]['top_left_corner'] = build_image('/icon/giftLuck.png');
                    }

                    //魔法彩蛋icon
                    $newYearGiftIds = [206,215,223,248,249,250];
                    if(in_array($counterArr[$k]['goods_id'],$newYearGiftIds)){
                        $counterArr[$k]['top_left_corner'] = build_image('/icon/magic.png');
                    }

                    //38活动icon
                    $minGiftIds = [254,255,256];
                    $iconStart = strtotime('2024-03-06 12:00:00');
                    $iconEnd = strtotime('2024-03-08 23:59:59');
                    if(in_array($counterArr[$k]['goods_id'],$minGiftIds) && (time()>=$iconStart && time()<= $iconEnd)){
                        $counterArr[$k]['top_left_corner'] = build_image('/icon/38.png');
                    }
                    
                    //如果礼物不显示
                    if($giftArr[$counterArr[$k]['goods_id']]['is_show'] != 1) {
                        unset($counterArr[$k]);
                    }
                }

                continue;
            }

        }

        foreach ($counterArr as $k => $v) {
            if (in_array($counterArr[$k]['goods_type'], [1])) {
                $counterArr[$k]['classification'] = $giftArr[$counterArr[$k]['goods_id']]['classification'] ?? 0;
                $counterArr[$k]['classification_config'] = $giftArr[$counterArr[$k]['goods_id']]['classification_config'] ?? new \stdClass();
            }
        }
        //专属礼物特权
        $counterArr = $this->modelGift->getGiftExclusive($counterArr, $cur_user_id);

        //礼物banner
        $counterArr = $this->adModel->getGiftBanner($counterArr, $cur_user_id);

        //礼物抵扣券
        $counterArr = $this->modelGift->getGiftDeduct($counterArr, $cur_user_id);

        $newArr = [];
        //获取活动模版开始时间结束时间 
        $customInfo = $this->customModel->getCumstomInfo($cur_user_id);
        $start = $customInfo['start_act'];
        $end = $customInfo['end_act']; 
        if((time() >= $start && time() <= $end ) && $cateId == 2){   
            $hotId = [226];
            //获取用户所持有的人气票数
            $res = $this->modelGiftBag->getNewGiftArr($cur_user_id, $hotId);
            foreach ($res as $val) {
                $result[] = [
                    'goods_type' => 1,
                    'pay_type' => 1,//默认
                    'goods_id' => $val['gift_id'],
                    'name' => $val['name'],
                    'explain' => '',
                    'image' => $val['image'],
                    'count' => isset($val['avail']) ? $val['avail'] : 0,
                    'price' => $val['price'] ?? 0,
                    'gift_resource' => $val['animate_resource'],
                    'label_image' => getFullImageUrl($this->modelGift->getGiftLabelRes($val['gift_label_id'], 'image')),
                    'no_sale' => 1, //1不可售卖 0可以售卖
                    'top_left_corner' => build_image('/icon/38.png')
                ];
            }
            $newArr = $this->adModel->getGiftBanner($result, $cur_user_id);
        }
        $data = [];
        $specList = $this->modelGift->getGiftSpec();
        $data['spec_list'] = array_column($specList, 'spec_num');
        $data['spec_list_name'] = array_column($specList, 'name');
        $data['list'] = array_values($counterArr);
        $data['other_gift_list'] = $newArr;

        return $data;
    }

    public function getMyCounter($userId)
    {
        $data = [];
        $giftArr = $this->modelGiftBag->getAll($userId);

        //活动模版人气票展示条件
        $customInfo = $this->customModel->getCumstomInfo($userId);
        
        $start = $customInfo['start_act'];
        $end = $customInfo['end_act']; 

        foreach ($giftArr as $val) {
            //人气票处理显示
            if((time() < $start && time() > $end) && $val['gift_id'] == 226){
                continue;
            }
            $data[] = [
                'goods_type' => 1,
                'goods_id' => $val['gift_id'],
                'name' => $val['name'],
                'explain' => '',
                'image' => $val['image'],
                'count' => $val['avail'],
                'price' => $val['price'] ?? 0,
                'gift_resource' => $val['animate_resource'],
                'wealth_num' => $val['wealth_num'],
                'label_image' => getFullImageUrl($this->modelGift->getGiftLabelRes($val['gift_label_id'], 'image')),
            ];
        }

        //礼物banner
        $data = $this->adModel->getGiftBanner($data, $userId);

        $ret = [];
        $specList = $this->modelGift->getGiftSpec();
        $ret['spec_list'] = array_column($specList, 'spec_num');
        $ret['spec_list_name'] = array_column($specList, 'name');
        $ret['list'] = $data;
        return $ret;
    }

    /**
     * 货架-更新或创建
     * */
    public function updateOrInsertCounter()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('goods_type', '货物类型', 'int', true);
            $this->I('goods_id', '商品Id', 'int', true);
            $this->I('name', '商品名称', 'string', false);
            $this->I('explain', '货物说明', 'string', false);
            $this->I('exp_icon_url', '扩展图标', 'string', false);
            $this->I('exp_url', '扩展action', 'string', false);
            $this->I('image', '货物图片', 'string', false);
            $this->I('counter_id', '货柜ID', 'int', true);
            $this->I('order', '排序', 'int', false);
            $this->I('id', 'id', 'int', false);
            $this->I('counter_cate_id', 'counter_cate_id', 'int', false);
            $this->I('start_time', '开始时间', 'int', false);
            $this->I('end_time', '结束时间', 'int', false);
            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $counterId = $this->requestData['id'] ?? 0;
            unset($this->requestData['id']);

            // 更新
            if ($counterId > 0) {
                $getPropById = $this->modelCounter->getCounterById($counterId);
                if (empty($getPropById)) {
                    $code = Hint::ERR_DATA_NOT_EXIST;
                    $msg = '货架' . Hint::getErrCodeMsg($code);
                    break;
                }

                $ret = $this->modelCounter->CUDCounter($this->requestData, 'update', $counterId);
                if (!$ret) {
                    $code = Hint::ERR_DATA_UPDATE_FAIL;
                    $msg = '货架' . Hint::getErrCodeMsg($code);
                    break;
                }
                $data['id'] = $counterId;
                break;
            }

            // 创建
            $ret = $this->modelCounter->CUDCounter($this->requestData, 'insert');
            if (!$ret) {
                $code = Hint::ERR_DATA_CREATE_FAIL;
                $msg = '货架' . Hint::getErrCodeMsg($code);
                break;
            }
            $data['id'] = intval($ret);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 货架-删除
     * */
    public function removeCounter()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('id', 'ID', 'int', true, 'ID不能为空');

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $ret = $this->modelCounter->CUDCounter([], 'delete', $this->requestData['id']);
            if (!$ret) {
                $code = Hint::ERR_DATA_REMOVE_FAIL;
                $msg = '货架' . Hint::getErrCodeMsg($code);
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }


    public function getCounterCate($counter_id, $roomId, $userId)
    {
        $list = $this->modelCounter->getCounterCate($counter_id, $roomId);
        //当前用户总充值金额
        $userRecharge = 0;
        if(!empty($userId)) {
            $userRecharge = $this->rechargeModel->getRechargeTotal($userId); //充值金额
        }

        //幸运礼物判断
        $listEx = [];
        foreach($list as $val) {
            if(!empty($val['if_room'])) {
                if(empty($roomId)) {
                    continue;
                }
            }

            if(!empty($val['minmoney'])) {
                if($userRecharge < $val['minmoney']) {
                    continue;
                }
            }
            if(!empty(Redis::get($this->roomTestList))){
                $roomlist = json_decode(Redis::get($this->roomTestList),true);
                if(!in_array($roomId,$roomlist) && in_array($val['counter_cate_id'],[52])){
                    continue;
                }
            }
            
            $listEx[] = $val;
        }

        $ret['list'] = $listEx;
        return $ret;
    }


    /**
     * 货架分类-更新或创建
     * */
    public function updateOrInsertCounterCate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('name', '商品名称', 'string', false);
            $this->I('counter_id', '货柜ID', 'int', false);
            $this->I('sort', '排序', 'int', false);
            $this->I('status', '状态', 'int', false);
            $this->I('id', 'ID', 'int', false);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $counterId = $this->requestData['id'] ?? 0;
            unset($this->requestData['id']);

            // 更新
            if ($counterId > 0) {
                $getPropById = $this->modelCounter->getCounterCateById($counterId);
                if (empty($getPropById)) {
                    $code = Hint::ERR_DATA_NOT_EXIST;
                    $msg = '货架' . Hint::getErrCodeMsg($code);
                    break;
                }

                $ret = $this->modelCounter->CUDCounterCate($this->requestData, 'update', $counterId);
                if (!$ret) {
                    $code = Hint::ERR_DATA_UPDATE_FAIL;
                    $msg = '货架' . Hint::getErrCodeMsg($code);
                    break;
                }
                $data['id'] = $counterId;
                break;
            }

            // 创建
            $ret = $this->modelCounter->CUDCounterCate($this->requestData, 'insert');
            if (!$ret) {
                $code = Hint::ERR_DATA_CREATE_FAIL;
                $msg = '货架' . Hint::getErrCodeMsg($code);
                break;
            }
            $data['id'] = intval($ret);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 货架-删除
     * */
    public function removeCounterCate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('id', 'ID', 'int', true, 'ID不能为空');

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $ret = $this->modelCounter->CUDCounterCate([], 'delete', $this->requestData['id']);
            if (!$ret) {
                $code = Hint::ERR_DATA_REMOVE_FAIL;
                $msg = '货架' . Hint::getErrCodeMsg($code);
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function createOrUpdateCounterNewPlay(array $data = [], int $id = 0, int $isDel = 0): int
    {
        if ($isDel) {
            return $this->modelCounter->deleteCounterNewPlay($id);
        }
        $action = !$id ? 'insertCounterNewPlay' : 'updateCounterNewPlay';
        Log::debug($action, ['id' => $id]);
        return $this->modelCounter->$action($data, $id);
    }

    public function getCounterByCounterId(int $counterId)
    {
        return $this->modelCounter->getCounterById($counterId);
    }

    // 升级礼物已发送总数数量
    public function getLevelGiftNum(int $userId, int $giftId): int
    {
        $record = $this->doubleHitStatistics->getSingle(['user_id' => $userId, 'gift_id' => $giftId], ['level', 'num'], true);
        if ($record) {
            return intval($record['num']);
        }
        return -1;
    }

}
